#ifndef __KERN_PROCESS_PROC_H__
#define __KERN_PROCESS_PROC_H__

#include <defs.h>
#include <list.h>
#include <trap.h>
#include <memlayout.h>


// 进程的状态
enum proc_state {
    PROC_UNINIT = 0,  // 未初始化
    PROC_SLEEPING,    // 休眠、阻塞状态 
    PROC_RUNNABLE,    // 可运行、就绪状态
    PROC_ZOMBIE,      // 僵尸状态，等待父线程回收
};

// Saved registers for kernel context switches.
// Don't need to save all the %fs etc. segment registers,
// because they are constant across kernel contexts.
// Save all the regular registers so we don't need to care
// which are caller save, but not the return register %eax.
// (Not saving %eax just simplifies the switching code.)
// The layout of context must match code in switch.S.
struct context {//进程运行的上下文（各个寄存器的状态）
    uint32_t eip;
    uint32_t esp;
    uint32_t ebx;
    uint32_t ecx;
    uint32_t edx;
    uint32_t esi;
    uint32_t edi;
    uint32_t ebp;
};

#define PROC_NAME_LEN               15
#define MAX_PROCESS                 4096
#define MAX_PID                     (MAX_PROCESS * 2)

extern list_entry_t proc_list;

//线程控制块
struct proc_struct {
    int pid;                                    // 进程ID
    char name[PROC_NAME_LEN + 1];               // 进程名字
    enum proc_state state;                      // 进程状态
    int runs;                                   // the running times of Proces
    volatile bool need_resched;                 // 是否需要调度
    uintptr_t kstack;                           // 进程内核堆栈,记录了分配给线程的内核栈的位置
    uintptr_t cr3;                              // 当前使用的页表的地址
    struct mm_struct *mm;                       // 描述进程虚拟内存的结构体，用来管理内存空间
    
    struct context context;                     // 进程运行的上下文
    struct trapframe *tf;                       // 中断帧的指针，指向内核栈的摸个位置
    
    uint32_t flags;                             // Process flag
    struct proc_struct *parent;                 // 父进程
    list_entry_t list_link;                     // Process link list 构成进程链表
    list_entry_t hash_link;                     // Process hash list 用于建立一个关于哈希值的链表便于快速查找
};

#define le2proc(le, member)         \
    to_struct((le), struct proc_struct, member)

extern struct proc_struct *idleproc, *initproc, *current;

void proc_init(void);
void proc_run(struct proc_struct *proc);
int kernel_thread(int (*fn)(void *), void *arg, uint32_t clone_flags);

char *set_proc_name(struct proc_struct *proc, const char *name);
char *get_proc_name(struct proc_struct *proc);
void cpu_idle(void) __attribute__((noreturn));

struct proc_struct *find_proc(int pid);
int do_fork(uint32_t clone_flags, uintptr_t stack, struct trapframe *tf);
int do_exit(int error_code);

#endif /* !__KERN_PROCESS_PROC_H__ */

